package com.ihome.android.market2.asynctask;

import java.io.File;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.ihome.android.academy.AppMgrActivity;
import com.ihome.android.academy.InitialActivity;
import com.ihome.android.academy.MainActivity;
import com.ihome.android.dl.core.DownloadTask;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.MyProgressDialog;
import com.ihome.android.util.BgInstallApk;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

/**
 * 安装应用
 * 
 * @author Emerson
 * 
 */
public class InstallAppTask extends AsyncTask<Bundle, Integer, Bundle> {
	private final String		TAG					= InstallAppTask.class.getSimpleName();
	private Context				context;
	private MyProgressDialog	progressDialog;
	private Object[]			installResult;
	private String				apkPath;
	private long				minAvailbleSpace	= 200;									//MB,低于此空间很多操作则受限制，如安装应用。
	/**
	 * 默认显示安装进度圈
	 */
	private boolean				showProgress		= true;

	public InstallAppTask(Context context) {
		this.context = context;
	}

	public InstallAppTask(Context context, boolean showProgress) {
		this.context = context;
		this.showProgress = showProgress;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if (showProgress) {
			progressDialog = MyProgressDialog.getDialog(context, context.getString(R.string.installing_app));
			progressDialog.show();
			progressDialog.setCancelable(false);
			progressDialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					if (InstallAppTask.this.getStatus().compareTo(AsyncTask.Status.FINISHED) != 0)
						InstallAppTask.this.cancel(true);
				}
			});
		}
	}

	@Override
	protected Bundle doInBackground(Bundle... params) {
		Bundle b = params[0];
		apkPath = b.getString(HttpKeys.KEY_APKPATH);

		if (TextUtils.isEmpty(apkPath)) {
			String[] msg1 = { "", "", "" , "", "InstallApk", "" };
			UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg1);
			return null;
		}
		LogUtil.v(TAG, "apkPath = " + apkPath);
		Object[] chmodRusult = BgInstallApk.excuteShellComm("chmod 777 " + apkPath);
		LogUtil.d(TAG, "chmodRusult = " + ((Boolean) chmodRusult[0]).booleanValue());

		installResult = BgInstallApk.installAppInBackGround(apkPath, "-r");
		LogUtil.v(TAG, "installResult = " + ((Boolean) installResult[0]).booleanValue());

		return b;
	}

	@Override
	protected void onPostExecute(Bundle result) {
		super.onPostExecute(result);
		if (progressDialog != null && progressDialog.isShowing())
			progressDialog.dismiss();

		if (result == null) {
			return;
		}

		//LogUtil.v(TAG, "Delete APK = " + new File(apkPath).delete());

		/** 安装失败处理 */
		if (((Boolean) installResult[0]).booleanValue() == false) {
			delDownloadFile(apkPath);
			String[] msgx = {"","","","","InstallApk",""};
			UserBehaviorLog.getInstance().writeLog(UserBehavior.APPDOWNLOAD_EXCEPTION, NotifyType.TYPE_NORMAL, "", msgx);
			
			if (((String) installResult[1]).contains("INSUFFICIENT_STORAGE")) {
				new DialogFactory(context).showDialog(context.getString(R.string.app_install_failure_lackspace));
			}
			else {
				new DialogFactory(context).showDialog(context.getString(R.string.app_install_failure));
			}
			return;
		}
		/** 安装成功处理 */
		//		else if (installResult && DetailActivity.class.isInstance(context)) {
		//			((DetailActivity) context).installationCheck(apkPath);
		//		}else if (installResult && AppMgrActivity.class.isInstance(context)) {
		//			((AppMgrActivity) context).installationCheck(apkPath);
		//		}

		if (((Boolean) installResult[0]).booleanValue() == true && AppMgrActivity.class.isInstance(context)) {
			((AppMgrActivity) context).installationCheck(apkPath);
		}
//		else if (((Boolean) installResult[0]).booleanValue() == true && MainActivity.class.isInstance(context)) {
//			((MainActivity) context).delAppStoreUpdatedAPK(apkPath);
//		}

		else if (((Boolean) installResult[0]).booleanValue() == true && InitialActivity.class.isInstance(context)) {
			((InitialActivity) context).finish();
		}
		new DialogFactory(context).showToast(context.getString(R.string.app_install_success), Toast.LENGTH_SHORT);

	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		LogUtil.i(TAG, "--> onCancelled");
		if (progressDialog != null)
			progressDialog.dismiss();
	}

	private void delDownloadFile(String filePath) {
		if (TextUtils.isEmpty(filePath)) {
			return;
		}
		else {
			File dwnFile = new File(filePath);
			File tmpdwnFile = new File(filePath + DownloadTask.TEMP_SUFFIX);
			if (dwnFile.exists()) {
				dwnFile.delete();
			}
			if (tmpdwnFile.exists()) {
				tmpdwnFile.delete();
			}
			dwnFile = null;
			tmpdwnFile = null;
		}
	}

}
